from rest_framework import serializers
from .models import KeyPart


class KeyPartSerializer(serializers.ModelSerializer):
    """关键备件序列化器"""
    
    class Meta:
        model = KeyPart
        fields = [
            'id',
            'item_name',
            'model', 
            'stock_in_quantity',
            'stock_in_time',
            'inventory_quantity',
            'used_quantity',
            'used_time',
            'purpose',
            'user_name',
            'remarks',
            'created_at',
            'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def to_representation(self, instance):
        """自定义序列化输出格式"""
        data = super().to_representation(instance)
        
        # 格式化时间字段
        if data.get('stock_in_time'):
            data['stock_in_time'] = instance.stock_in_time.strftime('%Y-%m-%d %H:%M:%S') if instance.stock_in_time else ''
        
        if data.get('used_time'):
            data['used_time'] = instance.used_time.strftime('%Y-%m-%d %H:%M:%S') if instance.used_time else ''
            
        return data